import {
  aes_decrypt,
  getSign,
  paramsEncrypt,
  rsaEncrypt,
} from '@/utils/security.js';
import utils from '@/utils/utils.js';
import MD5 from 'js-md5'; // MD5加密

// #ifdef H5
const Fly = require('flyio/dist/npm/fly');
// #endif

// #ifdef MP-WEIXIN || APP-PLUS
const Fly = require('flyio/dist/npm/wx');
const EngineWrapper = require('flyio/dist/npm/engine-wrapper');
const engine = EngineWrapper(function (request, responseCallback) {
  let con = {
    method: request.method,
    url: request.url,
    dataType: request.dataType || undefined,
    header: request.headers,
    data: request.body || {},
    responseType: request.responseType || 'text',
    sslVerify: false,
    success(res) {
      responseCallback({
        statusCode: res.statusCode,
        responseText: res.data,
        headers: res.header,
        statusMessage: res.errMsg,
      });
    },
    fail(res) {
      responseCallback({
        statusCode: res.statusCode || 0,
        statusMessage: res.errMsg,
      });
    },
  };
  wx.request(con);
});
// #endif

const { NODE_ENV, VUE_APP_PLATFORM, VUE_APP_BASE_URL } = process.env;
const isProxy = NODE_ENV == 'development' && VUE_APP_PLATFORM == 'h5';
const baseURL = isProxy
  ? '/energy-servicer-mapi/ser-mapi'
  : `${VUE_APP_BASE_URL}/energy-servicer-mapi/ser-mapi`;

let aesKey = ''; // 声明全局 aes 密钥
const fly = new Fly();

fly.config.baseURL = baseURL;
fly.interceptors.request.use(
  (request) => {
    //console.log(request.body);
    aesKey = utils.getAesKey(32); //每次匹配拦截 生成不同的 aes 密钥
    const token = uni.getStorageSync(
      'tokenSer' + process.env.VUE_APP_PLATFORMID
    );
    const DeviceType = uni.getSystemInfoSync().deviceType;
    const DeviceId = uni.getSystemInfoSync().deviceId;
    const TimeStamp = new Date().getTime();
    const RandomStrPlaintext = aesKey;
    //console.log(RandomStrPlaintext);
    const RandomStr = rsaEncrypt(RandomStrPlaintext);
    let sign = {
      PlatformId: process.env.VUE_APP_PLATFORMID,
      TimeStamp: TimeStamp.toString(),
      UserType: 'ser',
      TerminalType:
        uni.getSystemInfoSync().uniPlatform == 'web' ? 'h5' : 'android',
      Authorization: token ? token : RandomStrPlaintext,
      DeviceType: DeviceType,
      DeviceId: DeviceId,
      RandomStr: RandomStrPlaintext,
      body: request.body || {},
    };
    //console.log(request);
    request.body =
      request.type == 'encrypt'
        ? paramsEncrypt(request.body, aesKey)
        : getSign(request.body);
    //console.log(request.body);
    const newObj = getSign(sign);
    var Sign = JSON.stringify(newObj, (key, val) => {
      if (typeof val === 'undefined') {
        return '';
      }
      return val;
    });
    //console.log(Sign);
    Sign = MD5(Sign).toUpperCase();
    //console.log(Sign);
    (request.headers['Authorization'] = token ? token : RandomStrPlaintext),
      (request.headers['DeviceType'] = DeviceType);
    request.headers['DeviceId'] = DeviceId;
    request.headers['PlatformId'] = process.env.VUE_APP_PLATFORMID;
    request.headers['RandomStr'] = RandomStr;
    request.headers['Sign'] = Sign;
    request.headers['TerminalType'] =
      uni.getSystemInfoSync().uniPlatform == 'web' ? 'h5' : 'android';
    request.headers['TimeStamp'] = TimeStamp.toString();
    request.headers['UserType'] = 'ser';
    // #ifdef APP-PLUS
    request.headers['Version'] = uni.getStorageSync(
      'Version' + process.env.VUE_APP_PLATFORMID
    )
      ? uni.getStorageSync('Version' + process.env.VUE_APP_PLATFORMID)
      : plus.runtime.version;
    request.headers['DeviceBrand'] = uni.getSystemInfoSync().deviceBrand;
    console.log(request.headers);
    // #endif
    return request;
  },
  (error) => Promise.reject(error)
);

function decodeUnicode(str) {
  str = str.replace(/\\/g, '%');
  // 转换中文
  str = unescape(str);
  // 将其他受影响的转换回原来
  str = str.replace(/%/g, '\\');
  // 对网址的链接进行处理
  str = str.replace(/\\/g, '');
  return str;
}

//fly为需要登录的接口请求，fly2为不需要登录的接口请求
fly.interceptors.response.use(
  (response) => {
    //apptitle无该字段以及字段无值执行报错终止判断 => H5编译条件下
    // #ifdef H5
    if (response.headers.apptitle && response.headers.apptitle != null) {
      document.title = decodeUnicode(response.headers.apptitle);
    }
    // #endif
    const { code, msg } = response.data;
    if (code == 401) {
      uni.removeStorageSync('token');
      uni.removeStorageSync('expireAt');
      //store.commit('setUser', {});
      uni.reLaunch({
        url: '/login',
      });
    }
    if (code != 200) {
      uni.showToast({
        title: msg,
        icon: 'none',
      });
    }
    if (response.request.output == 'decrypt') {
      if (response.data.data) {
        response.data.data = JSON.parse(
          aes_decrypt(response.data.data, aesKey)
        );
      }
    }
    return response.data;
  },
  (error) => {
    console.log(error);
    return Promise.reject(error);
  }
);

// #ifdef MP-WEIXIN || APP-PLUS
fly.engine = engine;
// #endif

const fly2 = new Fly();

fly2.config.baseURL = baseURL;

fly2.interceptors.response.use(
  ({ data, request: { toast = true } }) => {
    const { code, msg } = data;
    if (code != 200 && toast) {
      uni.showToast({
        title: msg,
        icon: 'none',
      });
    }
    return data;
  },
  (error) => {
    const { response } = error;
    if (response) {
      const { status } = response;
      uni.showToast({
        title: `Request ${status}`,
        icon: 'none',
      });
    }
    return Promise.reject(error);
  }
);

// #ifdef MP-WEIXIN || APP-PLUS
fly2.engine = engine;
// #endif

export { fly, fly2 };
